$(function () {
    var layer = layui.layer;
    var form = layui.form;
    // 1-获取所有的分类信息
    initSwiperCateList();
    function initSwiperCateList() {
        $.ajax({
            type: 'get',
            url: '/admin/swipers',
            success: function (res) {
                if (res.status !== 0) {
                    return layer.msg(res.message);
                }
                var htmlStr = template('swiper-list', res);
                $('tbody').html(htmlStr)
            }
        })
    }

    // 2-状态栏
    $('.layui-table tbody').on('click', '.layui-badge', function (e) {
        let status = $(e.target).data('status')
        let id = $(e.target).data('id')
        $.ajax({
            type: 'put',
            url: '/admin/swipers/' + id,
            data: {
                status,
            },
            success: function (res) {
                if (res.status === 0) {
                    layer.msg(res.message)
                    initSwiperCateList();
                }
            }
        })
    })

    // 3-删除图片
    $('.layui-table tbody').on('click', '.btn-delete', function (e) {
        // 获取分类的id
        let id = $(e.target).data('id')
        // 询问
        layer.confirm('您确定要删除此项吗？', { icon: 3, title: '提示' }, function (index) {
            $.ajax({
                type: 'delete',
                url:'/admin/swipers/' + id,
                success: function (res) {
                    if (res.status !== 0) {
                        return layer.msg(res.message)
                    }
                    layer.msg('删除成功');
                    initSwiperCateList();
                }
            })
            layer.close(index)
        })
    })

    // 4-上传
    $('#uploadSwiper').click(function () {
        $('#myfile').click()
    })
    $('#myfile').change(function (e) {
        let files = e.target.files
        // console.log(files);
        var fd = new FormData()
        fd.append("swipers", files[0])
        $.ajax({
            type: 'post',
            url: '/admin/swipers',
            data: fd,
            processData: false,
            contentType: false,
            success: function (res) {
                if (res.status !== 0) {
                    return layer.msg(res.message)
                }
                initSwiperCateList();
            }
        })
    })
})